package com.jiangchuang.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.jiangchuang.domain.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

@Slf4j
@Component
public class OssUtils {
    @Resource
    public OssProperties ossProperties;

    public static OssUtils ossUtils;
    public static OSS oss;

    @PostConstruct
    public void init(){
        ossUtils=this;
        ossUtils.ossProperties=this.ossProperties;
        try{
            String endpoint = ossProperties.getEndpoint();
            oss = new OSSClientBuilder().build(endpoint, ossProperties.getAccessKey(), ossProperties.getSecretKey());
            log.info(">>>>>>>>>>>oss 初始化成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(">>>>>>>>>>>>>>>>初始化oss异常: 【{}】", e.fillInStackTrace());
        }
    }

    /**
     * 上传文件
     * @param dir
     * @param file
     * @return
     */
    public static String upload(String dir, MultipartFile file) {
        // 获取文件名称
        String sourceName = file.getOriginalFilename();

        // 获取地域节点
        String endpoint = ossUtils.ossProperties.getEndpoint();
        // 获取存储空间名称
        String bucketName = ossUtils.ossProperties.getBucketName();
        try{
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, dir, file.getInputStream());
            // 上传文件
            oss.putObject(putObjectRequest);
//            String url = "https://"+ossUtils.ossProperties.getBucketName()+"."+ossUtils.ossProperties.getEndpoint()+"/"+dir;
            return getFileUrl(bucketName, dir);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 上传文件流
     * dir : 不包含桶信息
     * @return
     */
    public static String upload(String dir, InputStream stream) {
        // 获取文件名称
//        String sourceName = file.getOriginalFilename();

        // 获取存储空间名称
        String bucketName = ossUtils.ossProperties.getBucketName();
        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, dir, stream);
        // 上传文件
        oss.putObject(putObjectRequest);
//        String url = "https://"+ossUtils.ossProperties.getBucketName()+"."+ossUtils.ossProperties.getEndpoint()+"/"+dir;
        return getFileUrl(bucketName, dir);
    }

    /**
     * 删除oss文件
     * @param objectName
     * @return
     */
    public static boolean deleteFile(String objectName){
        try {
//            String[] splitStr = objectName.split("https://"+ossUtils.ossProperties.getBucketName()+"."+ossUtils.ossProperties.getEndpoint()+"/");
            String[] splitStr = objectName.split(Global.getOssPrefix(ossUtils.ossProperties.getBucketName())+'/');

            if(splitStr.length<=1){
                // 再加一层判断文件域名为https://jiangchuang-test.oss-cn-hangzhou.aliyuncs.com/的
                splitStr = objectName.split("https://"+ossUtils.ossProperties.getBucketName()+"."+ossUtils.ossProperties.getEndpoint()+"/");
                if(splitStr.length<=1){
                    return true;
                }
            }

            boolean b = oss.doesObjectExist(ossUtils.ossProperties.getBucketName(), splitStr[1]);
            if(oss.doesObjectExist(ossUtils.ossProperties.getBucketName(), splitStr[1])){
                // 删除文件或目录。如果要删除目录，目录必须为空。
                oss.deleteObject(ossUtils.ossProperties.getBucketName(), splitStr[1]);
                log.info("【oss 删除文件】========="+splitStr[1]);
            }else{
                System.out.println(objectName);
            }
            System.out.println("is file exist:"+b);

            return true;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
            log.error("oss deleteFile failed" + oe.getErrorMessage());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
            log.error("oss deleteFile failed" + ce.getErrorMessage());

        }
        return false;
    }

    /**
     *
     * 获取oss文件的下载地址
     * @param bucketName 桶名
     * @param fileName  文件名
     */
    public static String getFileUrl(String bucketName, String fileName) {
        if(Objects.equals(bucketName, "jiangchuang-fanquan")){
            return Global.DOMAIN_NAME + "/oss/fanquan/"+fileName;
        } else if (Objects.equals(bucketName, "jiangchuang-test")) {
            return Global.DOMAIN_NAME + "/oss/fanquan-test/"+fileName;
        }
        return "";
    }

//
//    public static copyFile(){
//
//        // 拷贝文件。
//        CopyObjectResult result = oss.copyObject(sourceBucketName, sourceKey, destinationBucketName, destinationKey);
//        System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());
//    }

}
